/*
 * @ author madman 
 * @ use excel导入导出类
 */
const Utils = require('../utils');
const countryModel = require('../../models/nexmo/country.model');
const nodeExcel = require('node-excel')
const XLSX = require('node-xlsx')
// const Busboy = require('busboy')
var shortid = require('shortid');
const path = require('path');
const MathRound= function(val, type) {
  return (Math.round(val * (type || 100000)) / (type || 100000))
}
class Excel {
    // 导入
    async importExcel(ctx) {
      var files = ctx.request.files.file
      const ExcelObj = XLSX.parse(files.path)
      const modules= require(`../../models/nexmo/${ctx.request.body.price}.model`);
      var ExceData = []
      // var PriceList = modules.find({});
      ExcelObj[0].data.map((item,index) => {
        if (index > 0 && item.length > 0) {
          if (ctx.request.body.price === 'price') {
            ExceData.push({
              _id: item[0] + '',
              countryCode: item[1],
              countryName: item[2],
              monthPrice: MathRound(MathRound(item[3]), 10000) + '',
              inPriceCost: MathRound(MathRound(item[4]), 10000) + '',
              inPrice: MathRound(MathRound(item[5]), 10000) + '',
              telOutPrice: MathRound(MathRound(item[6]), 10000)  + '',
              mobileOutPrice: MathRound(MathRound(item[7]), 10000) + ''
            })
          }
          // 导入呼出价格
          if (ctx.request.body.price === 'priceout') {
            ExceData.push({
              _id: shortid.generate(),
              msisdn: ctx.request.body._id,
              countryCode: item[0],
              countryName: item[1],
              telOutPrice: MathRound(MathRound(item[2]), 10000)+ '',
              mobileOutPrice: MathRound(MathRound(item[3]), 10000)+ ''
            })
          }
        }
      })
      try {
        var countryExceData = []
        var  countryList = await countryModel.find({})
        if(countryList.length > 0) {
          countryList.map(item => {
            ExceData.map(data => {
              if (item.countryCode === data.countryCode) {
                countryExceData.push({
                  _id: data._id,
                  countryCode: data.countryCode,
                  countryName: data.countryName,
                  dialingPrefix: item.dialingPrefix,   //将国家区号导入
                  monthPrice: data.monthPrice,
                  inPriceCost: data.inPriceCost,
                  outPriceCost: MathRound(MathRound(parseFloat(item.defaultPrice)), 10000),//呼出成本导入
                  inPrice: data.inPrice,
                  telOutPrice: data.telOutPrice,
                  mobileOutPrice: data.mobileOutPrice
                })
              }
            })
          })
        }
        var isRemove = await  modules.collection.remove({})
        console.log('isRemove_'+isRemove)
        if (isRemove) {
          var res = await modules.collection.insertMany(ctx.request.body.price === 'price'? countryExceData : ExceData)
          if (res) {
            ctx.success({ msg: '导入成功' });
          } else {
            ctx.error({ msg: '导入失败' });
          }
        }
      } catch (err) {
        ctx.error({ msg: '有重复数据不能继续导入'});
      }
    }
    // 导出
    async exportExcel(ctx) {
      let ExcelConf ={};
      const moduleName = require(`../../models/${ctx.body.query.model}.model`);
      conf.name = ctx.body.query.excelName  //定义表格名
      var ExcelData = moduleName.find({},{__v: 0 , _id: 0})
      //决定列名和类型
      var ExcelKeys= Object.keys(ExcelData[0])
      ExcelConf.cols = ExcelKeys.map(item => {
        return {
          caption:item,
          type:'string'
        }
      })
      ExcelConf.rows = ExcelData;//填充数据
      let result = nodeExcel.execute(ExcelConf);
      let data = new Buffer(result, 'binary');
      ctx.set('Content-Type', 'application/vnd.openxmlformats');
      ctx.set("Content-Disposition", "attachment; filename=" + "Report.xlsx");
      ctx.body=data;
  }
}

export default new Excel;